// app.js
const express = require('express')
const mysql = require('mysql')
const app = express()
const port = 3000
var mysqlconfig = {
  host: '127.0.0.1',
  user: 'root',
  password: '123456',
  database: 'student',
  port: 3306
};

let con = mysql.createConnection(mysqlconfig)
con.connect();

var bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.all('*', function (req, res, next) {
  // 设置是否运行客户端设置 withCredentials
  // 即在不同域名下发出的请求也可以携带 cookie
  res.header("Access-Control-Allow-Credentials", true)
  // 第二个参数表示允许跨域的域名，* 代表所有域名  
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS') // 允许的 http 请求的方法
  // 允许前台获得的除 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 这几张基本响应头之外的响应头
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
  if (req.method == 'OPTIONS') {
    res.sendStatus(200)
  } else {
    next()
  }
});


app.get('/', (req, res) => {
  res.send('Hello World!')
})

// 登录

app.get('/login', (req, res) => {
  console.log(req.query)
  res.header('Access-Control-Allow-Origin', '*')
  var name = req.query.uname;
  var pass = req.query.pword;
  if (name == "zhangsan" && pass == "123") {
    res.send("1")
  } else {
    res.send("0")
  }
})

// 注册 get  post 

app.post('/register', (req, res) => {
  res.header('Access-Control-Allow-Origin', '*')
  // console.log(req.body)

  let username = req.body.uname;
  let password = req.body.pword;
  let email = req.body.email;
  // 创建sql 语句
  let sql = "insert into users values(" + username + "," + password + "," + email + ");";
  con.query(sql, function (err, rs) {
    if (err) {
      console.log(err);
    } else {
      if (rs.affectedRows >= 1) { //增、删、改的操作，都会使受影响的函发生改变
        res.send("1");  //1为注册成功
        console.log("1为注册成功")
        res.end()
      } else {
        res.send("0"); //新增失败
        console.log("数据库插入成功")
        res.end()
      }

    }
  }
  );
  con.end();


})

//   get post
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

